﻿using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Cms.Web.Framework.Infrastructure;

namespace Cms.Web.Framework
{
    public class UrlSnapshotGenerator : IDisposable
    {
        private readonly ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
        private readonly string _url;
        private readonly Size _emulatedBrowserSize;
        private readonly Size _thumbnailSize;
        private Bitmap _image;

        private const int EmulatedBrowserPageLoadTimeout = 5; // this could be adjusted up or down
        
        public UrlSnapshotGenerator(string url, Size emulatedBrowserSize, Size thumbnailSize)
        {
            _url = url;
            _emulatedBrowserSize = emulatedBrowserSize;
            _thumbnailSize = thumbnailSize;
        }

        public Bitmap Image
        {
            get { return _image; }
        }
        
        public Bitmap GetSnapshot()
        {
            var thread = new Thread(ProcessSnapshot);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            _manualResetEvent.WaitOne();
            thread.Abort();
            return _image;
        }

        public void Dispose()
        {
            if (_image != null) _image.Dispose();
        }
        
        private void ProcessSnapshot()
        {
            var webBrowser = new WebBrowser { ScrollBarsEnabled = false };
            DateTime time = DateTime.Now;
            webBrowser.Navigate(_url);
            webBrowser.DocumentCompleted += WebBrowser_DocumentCompleted;
            while (true)
            {
                Thread.Sleep(0);
                TimeSpan elapsedTime = DateTime.Now - time;
                if (elapsedTime.Seconds >= EmulatedBrowserPageLoadTimeout)
                {
                    _manualResetEvent.Set();
                }
                System.Windows.Forms.Application.DoEvents();
            }
        }
        
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var webBrowser = (WebBrowser)sender;
            webBrowser.ClientSize = _emulatedBrowserSize;
            webBrowser.ScrollBarsEnabled = false;
            _image = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
            webBrowser.BringToFront();
            webBrowser.DrawToBitmap(_image, webBrowser.Bounds);
            Image img = ImageResizer.Resize(_image, _thumbnailSize);
            _image = (Bitmap)img;
            webBrowser.Dispose();
            if (_manualResetEvent != null)
            {
                _manualResetEvent.Set();
            }
        }
    }
}